package com.kexun.resolver;

import com.kexun.annotation.LoginManage;
import com.kexun.entity.DO.Manage;
import com.kexun.service.ManageService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * 有@LoginManage注解的方法参数，注入当前登录用户
 *
 * @author lidong
 * @email 3275208135@qq.com
 * @date 2020-04-08
 */
public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private ManageService manageService;

    public LoginUserHandlerMethodArgumentResolver(ManageService userService) {
        this.manageService = userService;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.getParameterType().isAssignableFrom(Manage.class) && parameter.hasParameterAnnotation(LoginManage.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request, WebDataBinderFactory factory) throws Exception {
        //获取用户ID
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        if (principal != null) {
            int userId = (int) principal;
            return manageService.findUserById(userId);
        }
        return null;

    }
}
